﻿using Dapper.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Enums;
using YouWei.Infrastructure.Models;
using YouWei.Infrastructure.Service;
using YouWei.Op.Common;
using YouWei.Op.Models.Live;
using YouWei.Utility;
using YouWei.Utility.Logging;

namespace YouWei.Op.Controllers
{
    public class LiveController : BaseController
    {
        private LiveRoomService lrService = new LiveRoomService();
        private LiveCommentService lcService = new LiveCommentService();
        private UserInfoService userService = new UserInfoService();

        string ImagesUrl = ConfigHelper.GetAppSettingValue("CommentImageServerUrl");

        #region 直播室
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ContentResult GetLiveRoomList(ReqLiveRoomCondition model)
        {
            int pageIndex = GetPageIndex();
            int pageSize = GetPageSize();
            Page<LiveRoomPage> lpage = new Page<LiveRoomPage>();
            List<LiveRoomPage> list = new List<LiveRoomPage>();

            Page<LiveRoom> page = lrService.GetPages(pageIndex, pageSize, model);

            //处理枚举字段
            page.rows.ForEach(item =>
            {
                var p = new LiveRoomPage();
                item.MergeTo(p);
                p.CoverImageUrl = string.Format("{0}/{1}", ImagesUrl, item.CoverImage);
                p.StatusName = EnumHelper.GetEnumDesc(typeof(LiveRoomStatus), item.Status);
                list.Add(p);
            });

            lpage.rows = list;
            lpage.total = page.total;
            return ReturnResult(lpage);
        }

        public ActionResult LiveRoomEdit()
        {
            LiveRoom info = new LiveRoom();
            int id = EConvert.ToInt(GetParam("id"), 0);
            if (id > 0)
            {
                info = lrService.Single(id);
            }
            return View(info);
        }

        /// <summary>
        /// 保存用户
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ContentResult SaveLiveRoom(LiveRoom reqModel)
        {
            var res = new ResultData<string>();
            LiveRoom info = null;

            if (reqModel.RoomID > 0)
            {
                info = lrService.Single(reqModel.RoomID);
                info.UpdatedTime = DateTime.Now;
                info.UpdatedUserID = CurrentUser.UserId;
            }
            else
            {
                info = new LiveRoom();
                info.CreatedTime = DateTime.Now;
                info.CreatedUserID = CurrentUser.UserId;
                info.IsActive = 1;
                info.UpdatedTime = DefaultTime;
            }

            info.Name = reqModel.Name;
            info.StartTime = reqModel.StartTime;
            info.CoverImage = reqModel.CoverImage;
            info.UserID = reqModel.UserID;
            info.OpenID = reqModel.OpenID;
            info.Status = 1;
            info.MaxPerson = reqModel.MaxPerson;
            info.Description = reqModel.Description;
            info.Duration = reqModel.Duration;
            info.WeChartUserHead = GetWxUserHeadUrl(reqModel.UserID);
            try
            {
                if (info.RoomID <= 0)
                {
                    object id = lrService.Insert(info);
                }
                else
                {
                    lrService.Update(info);
                }
                res.message = "成功";
                res.status = 0;
            }
            catch (Exception ex)
            {
                Log4netLog.Error(ex);
                res.message = "添加失败";
                res.status = -1;

            }
            return ReturnResult(res);
        }

        private string GetWxUserHeadUrl(int userId)
        {
            UserInfo info = userService.Single(userId);
            if (info!=null)
            {
                if (info.UserHead.StartsWith("https://"))
                {
                    return info.UserHead;
                }
                else
                {
                    return string.Format("{0}/{1}", Utility.ConfigHelper.GetAppSettingValue("CommentImageServerUrl"), info.UserHead);
                }
            }
            return "";
        }

        /// <summary>
        /// 直播室
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult DelLiveRoom(int id)
        {
            ResultData<bool> rData = new ResultData<bool>();
            if (id < 1)
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                return ReturnResult(rData);
            }
            LiveRoom info = lrService.Single(id);
            if (info != null)
            {
                info.IsActive = 0;
                info.UpdatedTime = DateTime.Now;
                info.UpdatedUserID = CurrentUser.UserId;
                lrService.Update(info);
                rData.status = 0;
                rData.data = true;
            }
            else
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                rData.data = false;
            }
            return ReturnResult(rData);
        }
        #endregion

        #region 评论
        public ActionResult Comment(int rid)
        {
            ViewBag.RoomId = rid;
            return View();
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ContentResult GetLiveCommentList(ReqLiveCommentCondition model)
        {
            int pageIndex = GetPageIndex();
            int pageSize = GetPageSize();

            Page<LiveCommentDto> page = lcService.GetPages(pageIndex, pageSize, model);
            return ReturnResult(page);
        }
        #endregion
    }
}